<template>
  <el-dialog title="分配权限" :visible="showDialog" @close="closeFn">
    <el-tree
      ref="tree"
      :data="permList"
      check-strictly
      show-checkbox
      highlight-current
      node-key="id"
      default-expand-all
      :props="{label:'name'}"
    />
    <template v-slot:footer>
      <el-row type="flex" justify="center">

        <el-button type="primary" @click="comfirmFn">确定</el-button>
        <el-button @click="closeFn">取消</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { getPermissions } from '@/api/permission'
import { assignPerm, getRoleDetailById } from '@/api/setting'
import { listToTree } from '@/utils'

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      permList: [],
      permIds: [],
      roleId: ''
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {

    async getPermissionList() {
      const res = await getPermissions()
      console.log(listToTree(res, '0'))
      this.permList = listToTree(res, '0')
    },
    async getPermIds(id) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const res = await getRoleDetailById(id)
      console.log('getRoleDetailById', res)
      this.roleId = id
      this.permIds = res.permIds
      this.$refs.tree.setCheckedKeys(this.permIds)
      loading.close()
    },
    closeFn() {
      this.$emit('update:showDialog', false)
      this.permIds = []
      this.$refs.tree.setCheckedKeys(this.permIds)
    },

    // 编辑角色
    async  editRole(id) {
      this.userId = id // props传值 是异步的
      await this.$refs.assignRole.getUserDetailById(id) // 父组件调用子组件方法
      this.showRoleDialog = true
    },
    async comfirmFn() {
      const permIds = this.$refs.tree.getCheckedKeys()
      await assignPerm({
        id: this.roleId,
        permIds
      })
      this.$emit('update:showDialog', false)
    }

  }
}
</script>

<style>

</style>
